<template>
  <!--ADX消耗管理-->
  <div>
    <SectionContainer class="u-p20">
      <SectionTitle>ADX消耗管理</SectionTitle>

      <!-- 筛选 start -->
      <el-form
        class="m-filter"
        inline
      >
        <el-form-item>
          <el-date-picker
            :clearable="false"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="u-w300"
            value-format="yyyy-MM-dd"
            :picker-options="DATERANGE_OPTIONS"
            v-model="filter.daterange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            size="small"
            filterable
            placeholder="请选择投放ADX"
            v-model="filter.adxId"
          >
            <el-option
              v-for="item in adMarketOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <TableFull
        :data="tableData"
        :total="tableTotal"
        :current-page="page.pageNo"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
        <el-form
          class="m-filter"
          inline
          slot="handle"
        >
          <el-form-item v-permission="['financial_adxConsum_import']">
            <el-upload
              :action="`${UPLOAD_BASE_URL}/manage/api/bus/financial/uploadflie`"
              :headers="{'x-access-token': token}"
              :show-file-list="false"
              :on-success="importSuccess"
              :before-upload="importBeforeUpload"
            >
              <el-button size="small">导入数据</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item v-permission="['financial_adxConsum_import']">
            <el-button
              size="small"
              @click="importTemplate"
            >下载模板</el-button>
          </el-form-item>
        </el-form>
        <template slot="column">
          <el-table-column
            :resizable="false"
            align="center"
            v-for="(item, index) in tableColumn"
            :width="item.width"
            :key="index"
            :label="item.label"
            :sort-by="item.prop"
          >
            <el-table-column
              :resizable="false"
              align="center"
              :label="item.prop === 'reportTime' ? '总计' : getTableDataSumValue(item.prop, {rate: []})"
              :width="item.width"
              :prop="item.prop"
              class-name="u-table--total"
            >
              <template slot-scope="scope">
                <!-- 投放ADX -->
                <template v-if="item.prop === 'union'">{{`${scope.row.unionName}(${scope.row.unionId})`}}</template>
                <!-- 其他 -->
                <template v-else>{{scope.row[item.prop]}}</template>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </TableFull>
    </SectionContainer>

    <!-- 导入完成的提示 -->
    <DialogImport
      :visible.sync="importVisible"
      :fail="importData.fail"
      :success="importData.success"
      :messages="importData.messages"
    ></DialogImport>
  </div>
</template>

<script>
import Moment from "moment";

import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import DialogImport from "@/components/dialog-import";
import TableFull from "@/components/table-full";

import DATERANGE_OPTIONS from "@/assets/js/daterange-option";
import { sessionStorage } from "@/utils";
import { decimalMultiply } from "@/utils/decimal";
import permissionMixin from "@/mixins/permission";
import { fetchAdxSelect, fetchFinancialAdxConsumeList } from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    SectionContainer,
    SectionTitle,
    DialogImport,
    TableFull
  },
  data() {
    return {
      UPLOAD_BASE_URL: process.env.VUE_APP_UPLOAD_BASE_URL,
      token: sessionStorage.get("USER").token,

      DATERANGE_OPTIONS,

      // 导入弹窗
      importVisible: false,
      importLoading: null,
      importData: {},

      // 下拉
      adMarketOptions: [],

      // 筛选
      filter: {
        daterange: [
          Moment()
            .subtract(3, "months")
            .format("YYYY-MM-DD"),
          Moment().format("YYYY-MM-DD")
        ],
        adxId: ""
      },

      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 表格
      tableColumn: [
        {
          label: "日期",
          prop: "reportTime"
        },
        {
          label: "投放ADX",
          prop: "union"
        },
        {
          label: "DSP消耗(元)",
          prop: "biddingCost"
        },
        {
          label: "ADX消耗(元)",
          prop: "mediaCost"
        },
        {
          label: "盈利金额(元)",
          prop: "profitAmount"
        }
      ],
      tableData: [],
      tableTotal: 0
    };
  },
  methods: {
    // adx下拉
    fetchAdxSelect() {
      return fetchAdxSelect({
        query: {
          unionId: 0 // adx，默认
        }
      }).then(res => {
        this.adMarketOptions = [
          {
            id: "",
            name: "全部adx"
          }
        ].concat(res.data.list);
      });
    },
    // 下载模板
    importTemplate() {
      location.href = "/xls/finance-adx-expend-template.xls";
    },
    // 导入数据
    importSuccess(res) {
      if (res.code === 0) {
        this.importVisible = true;
        this.importData = res.data;
        this.getTable();
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
      this.importLoading.close();
    },
    importBeforeUpload(file) {
      const type = /\.xlsx?$/.test(file.name);
      if (!type) {
        this.$message.error("请上传excel格式的文件");
      }
      this.importLoading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      return type;
    },
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchFinancialAdxConsumeList({
        body: {
          ...this.page,
          adxId: this.filter.adxId,
          startTime: this.filter.daterange[0],
          endTime: this.filter.daterange[1]
        }
      }).then(res => {
        this.tableTotal = res.data.count;
        if (res.data.list && res.data.list.length) {
          this.tableData = this.modTableDataSumList(
            res.data.sumList,
            res.data.list
          );
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return decimalMultiply(value, 100) + "%";
        }
        return String(value);
      }
      return "";
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    }
  },
  created() {
    this.fetchAdxSelect();
    this.getTable();
  }
};
</script>